package cn.smart.epic.modular.system.controller;

import cn.smart.epic.common.annotion.Permission;
import cn.smart.epic.common.annotion.log.BussinessLog;
import cn.smart.epic.common.constant.Const;
import cn.smart.epic.common.constant.Dict;
import cn.smart.epic.common.constant.state.ManagerStatus;
import cn.smart.epic.common.controller.BaseController;
import cn.smart.epic.common.exception.BizExceptionEnum;
import cn.smart.epic.common.exception.BussinessException;
import cn.smart.epic.common.page.PageReq;
import cn.smart.epic.common.persistence.dao.UserMapper;
import cn.smart.epic.common.persistence.model.User;
import cn.smart.epic.core.log.LogObjectHolder;
import cn.smart.epic.core.shiro.ShiroKit;
import cn.smart.epic.core.shiro.ShiroUser;
import cn.smart.epic.core.util.CommonUtil;
import cn.smart.epic.core.util.ToolUtil;
import cn.smart.epic.modular.system.factory.UserFactory;
import cn.smart.epic.modular.system.transfer.UserDto;
import cn.smart.epic.modular.system.warpper.UserWarpper;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @Auther Uncle_Z
 * @date 2018/7/25 16:51
 * @Email:2545375@qq.com
 * @Descrition
 * @since 1.0
 */

@Api(value = "/mgr",tags="用户管理模块")
@RestController
@RequestMapping(value = "/mgr/")
public class UserMgrController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(UserMgrController.class);

    @Autowired
    private UserMapper userMapper;

    @GetMapping("list")
    @Permission()
    public JSONObject list(String name,String beginTime,String endTime){
        PageReq pageReq = defaultPage();
        Page page= PageHelper.startPage(pageReq.getOffset(),pageReq.getLimit(),true);
        List<JSONObject> userList = userMapper.selectUsers(name,beginTime,endTime);
        return CommonUtil.successPage(((List<JSONObject>) new UserWarpper(userList).warp()),page.getTotal());
    }

    @PostMapping("add")
    @Permission(Const.ADMIN_NAME)
    @BussinessLog(name = "添加管理员",key="account",dict = cn.smart.epic.common.constant.Dict.UserDict)
    public JSONObject add(@RequestBody @Valid UserDto user, BindingResult result){
        if(result.hasErrors()){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }

        User theUser = userMapper.getByAccount(user.getAccount());
        if (theUser!=null) {
            throw new BussinessException(BizExceptionEnum.USER_ALREADY_REG);
        }

        // 完善账号信息
        user.setSalt(ShiroKit.getRandomSalt(5));
        user.setPassword(ShiroKit.md5(user.getPassword(), user.getSalt()));
        user.setStatus(ManagerStatus.OK.getCode());
        user.setCreatetime(new Date());

        userMapper.insert(UserFactory.createUser(user));
        return CommonUtil.successJson();
    }

    @PutMapping("edit")
    @BussinessLog(name = "修改管理员", key = "account", dict = Dict.UserDict)
    public JSONObject edit(@RequestBody @Valid UserDto user,BindingResult result,HttpServletRequest request){
        if(result.hasErrors()){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        User oldUser = userMapper.selectByPrimaryKey(user.getId());
        LogObjectHolder.me().set(oldUser);


        if(ShiroKit.hasRole(Const.ADMIN_NAME)){
            userMapper.updateByPrimaryKeySelective(UserFactory.createUser(user));
            return CommonUtil.successJson();
        }else{
            ShiroUser shiroUser = ShiroKit.getUser();
            if (shiroUser.getId().equals(user.getId())) {
                userMapper.updateByPrimaryKeySelective(UserFactory.createUser(user));
                return CommonUtil.successJson();
            } else {
                throw new BussinessException(BizExceptionEnum.NO_PERMITION);
            }
        }
    }

    @DeleteMapping("delete")
    @Permission
    @BussinessLog(name = "删除管理员",key = "userId",dict = Dict.UserDict)
    public JSONObject delete(Integer userId){
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能删除超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new BussinessException(BizExceptionEnum.CANT_DELETE_ADMIN);
        }
        userMapper.setStatus(userId,ManagerStatus.DELETED.getCode());
        return CommonUtil.successJson();
    }

    @GetMapping("reset")
    @BussinessLog(name = "重置管理员密码",key="userId",dict = Dict.UserDict)
    @Permission(Const.ADMIN_NAME)
    public JSONObject reset(Integer userId){
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        User user = userMapper.selectByPrimaryKey(userId);
        user.setSalt(ShiroKit.getRandomSalt(5));
        user.setPassword(ShiroKit.md5(Const.DEFAULT_PWD, user.getSalt()));
        userMapper.updateByPrimaryKey(user);
        return CommonUtil.successJson();
    }

    /**
     * 冻结用户
     */
    @GetMapping("freeze")
    @BussinessLog(name = "冻结用户", key = "userId", dict = Dict.UserDict)
    @Permission(Const.ADMIN_NAME)
    public JSONObject freeze(Integer userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能冻结超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new BussinessException(BizExceptionEnum.CANT_FREEZE_ADMIN);
        }
        userMapper.setStatus(userId, ManagerStatus.FREEZED.getCode());
        return CommonUtil.successJson();
    }

    /**
     * 解除冻结用户
     */
    @GetMapping("unfreeze")
    @BussinessLog(name = "解除冻结用户", key = "userId", dict = Dict.UserDict)
    @Permission(Const.ADMIN_NAME)
    public JSONObject unfreeze(Integer userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        userMapper.setStatus(userId, ManagerStatus.OK.getCode());
        return CommonUtil.successJson();
    }

    /**
     * 分配角色
     */
    @GetMapping("setRole")
    @BussinessLog(name = "分配角色", key = "userId,roleIds", dict = Dict.UserDict)
    @Permission(Const.ADMIN_NAME)
    public JSONObject setRole(@RequestParam("userId") Integer userId, @RequestParam("roleIds") String roleIds) {
        if (ToolUtil.isOneEmpty(userId, roleIds)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能修改超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new BussinessException(BizExceptionEnum.CANT_CHANGE_ADMIN);
        }
        userMapper.setRoles(userId, roleIds);
        return CommonUtil.successJson();
    }

}
